<template>
  <outMain>
    <div class="tableCont">
      <div class="page-title">
        <span class="title-text">商品列表</span>
        <div class="title-decoration"></div>
      </div>
      <div class="tableHead">
        <div class="formInput">
          <input
            v-model="queryData.search_key"
            placeholder="请输入需要查询的商品名称"
          />
        </div>
        <el-button @click="searchFn" class="public-button">
          <span class="iconfont icon-sousuo"></span>
          <span>查询</span>
        </el-button>
        <el-button @click="resetSearch" class="public-button reset-button">
          <span class="iconfont icon-zhongzhi"></span>
          <span>重置</span>
        </el-button>
        <el-button @click="addFn" class="public-button">
          <span class="iconfont icon-xinzeng"></span>
          <span>新增</span>
        </el-button>
      </div>
      <el-table class="tableMain" :data="tableData" stripe>
        <el-table-column prop="image" show-overflow-tooltip label="商品图片">
          <template #default="{ row }">
            <img class="tableImg" :src="row.image" alt="商品图片" />
          </template>
        </el-table-column>
        <el-table-column prop="name" show-overflow-tooltip label="商品名称" />
        <el-table-column prop="price" show-overflow-tooltip label="商品价格" />
        <el-table-column show-overflow-tooltip label="是否上架">
          <template #default="{ row }">
            <switchComponent
              :disabled="disStatus"
              @change="checkStatusFn(row)"
              v-model="row.status"
            />
          </template>
        </el-table-column>
        <el-table-column prop="stock" show-overflow-tooltip label="商品库存" />
        <el-table-column
          prop="create_time"
          show-overflow-tooltip
          label="创建时间"
        />
        <el-table-column width="140" label="操作">
          <template #default="{ row }">
            <div class="tableCtrl">
              <div class="action-cell">
                <div class="action-btn detail-btn" @click="handleDetail(row)">
                  <span class="iconfont icon-xiangqing-heliuxiangqing"></span>
                </div>
                <div class="action-btn edit-btn" @click="handleEdit(row)">
                  <span class="iconfont icon-bianji1"></span>
                </div>
                <div class="action-btn delete-btn" @click="handleDelete(row)">
                  <span class="iconfont icon-shanchu11"></span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pageCont">
        <cool-pagination
          v-model:current-page="queryData.page"
          :page-size="queryData.per_page"
          :total="total"
          @current-change="handlePageChange"
        />
      </div>
    </div>
    <!-- 商品表单弹窗 -->
    <cool-dialog
      v-model="showMaskForm"
      :title="isEdit ? '编辑商品' : '新增商品'"
      @confirm="confirmDialog"
      width="800px"
    >
      <div class="mask-form">
        <div class="form-group">
          <label class="form-label"
            >商品名称 <span class="required">*</span></label
          >
          <input
            type="text"
            v-model="formData.name"
            class="form-input"
            placeholder="请输入商品名称"
          />
        </div>
        <div class="form-group">
          <label class="form-label"
            >商品图片 <span class="required">*</span></label
          >
          <cropper @ok="getImage" :propImg="formData.image"></cropper>
        </div>

        <div class="form-group">
          <label class="form-label"
            >商品价格 <span class="required">*</span></label
          >
          <input
            type="number"
            v-model="formData.price"
            class="form-input"
            placeholder="请输入商品价格"
          />
        </div>

        <div class="form-group">
          <label class="form-label"
            >商品库存 <span class="required">*</span></label
          >
          <input
            type="number"
            v-model="formData.stock"
            class="form-input"
            placeholder="请输入商品库存"
          />
        </div>

        <!-- 商品分类 -->
        <div class="form-group">
          <label class="form-label">商品标签</label>
          <checkbox :checkboxList="availableTags" v-model="formData.tags" />
        </div>

        <div class="form-group">
          <label class="form-label">商品描述</label>
          <textarea
            v-model="formData.description"
            class="form-textarea"
            placeholder="请输入商品描述"
          ></textarea>
        </div>

        <!-- 详情图片 -->
        <div class="form-group">
          <label class="form-label"
            >商品详情图 <span class="required">*</span></label
          >
          <CoolImageUploadVue
            :maxCount="10"
            multiple
            :value="formData.detail_images"
            @ok="updateDetailImage"
          ></CoolImageUploadVue>
        </div>
        <div class="form-group">
          <label class="form-label">商品详情描述</label>
          <textarea
            v-model="formData.detail_descriptions"
            class="form-textarea"
            placeholder="请输入商品详情描述"
          ></textarea>
        </div>
        <div class="setting-item">
          <div class="setting-info">
            <div class="setting-title">是否启用</div>
            <div class="setting-desc">商品状态：关闭将无法展示</div>
          </div>
          <switchComponent v-model="formData.status" />
        </div>
      </div>
    </cool-dialog>
    <cool-dialog
      :overHidden="true"
      v-model="showReviewMask"
      title="审批详情"
      @confirm="confirmReview"
      width="800px"
    >
      <div class="maskInfo">
        <div class="review-details">
          <div class="section basic-info">
            <h3 class="section-title">
              <span class="iconfont icon-xiangqing-heliuxiangqing"></span>
              基本信息
            </h3>
            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">商品名称：</span>
                <span class="info-value">商品名称</span>
              </div>
              <div class="info-item">
                <span class="info-label">申请状态：</span>
                <span class="info-value">
                  <el-tag>待审核</el-tag>
                </span>
              </div>
              <div class="info-item">
                <span class="info-label">创建时间：</span>
                <span class="info-value">2025-08-18 10:00:00</span>
              </div>
            </div>
          </div>

          <div class="section trading-info">
            <h3 class="section-title">
              <span class="iconfont icon-jiaoyi"></span>
              交易信息
            </h3>
            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">挂牌金额：</span>
                <span class="info-value">0元</span>
              </div>
              <div class="info-item">
                <span class="info-label">保证金：</span>
                <span class="info-value">0元</span>
              </div>
              <div class="info-item">
                <span class="info-label">交易方式：</span>
                <span class="info-value">一口价</span>
              </div>
              <div class="info-item">
                <span class="info-label">交割周期：</span>
                <span class="info-value">1天</span>
              </div>
              <div class="info-item">
                <span class="info-label">项目类别：</span>
                <span class="info-value">1天</span>
              </div>
              <div class="info-item">
                <span class="info-label">项目所在地：</span>
                <span class="info-value">1天</span>
              </div>
              <div class="info-item">
                <span class="info-label">权属类型：</span>
                <span class="info-value">1天</span>
              </div>
            </div>
          </div>
          <div class="section time-info">
            <h3 class="section-title">
              <span class="iconfont icon-shijian"></span>
              竞标时间
            </h3>
            <div class="info-grid">
              <div class="info-item wide">
                <span class="info-label">开始时间：</span>
                <span class="info-value">2025-08-18 10:00:00</span>
              </div>
              <div class="info-item wide">
                <span class="info-label">结束时间：</span>
                <span class="info-value">2025-08-18 10:00:00</span>
              </div>
            </div>
          </div>

          <div class="section formImgs">
            <h3 class="section-title">
              <span class="iconfont icon-tupian"></span>
              挂牌图片
            </h3>
            <div
              class="images-container"
              v-if="reviewForm.listing_images.length > 0"
            >
              <viewImg
                v-for="(item, index) in reviewForm.listing_images"
                :key="index"
                :url="item.img"
              />
            </div>
            <div class="no-images" v-else>暂无挂牌图片</div>
          </div>

          <div class="section area_text">
            <h3 class="section-title">
              <span class="iconfont icon-gonggao"></span>
              挂牌公告
            </h3>
            <div class="area_text-content">暂无挂牌公告</div>
          </div>
        </div>
      </div>
    </cool-dialog>
  </outMain>
</template>

<script>
import CoolPagination from "@/components/CoolPagination.vue";
import CoolDialog from "@/components/CoolDialog.vue";
import outMain from "@/components/outMain.vue";
import cropper from "@/components/public/cropper.vue";
import checkbox from "@/components/form/checkbox.vue";
import switchComponent from "@/components/form/switch.vue";
import CoolImageUploadVue from "@/components/upload/CoolImageUpload.vue";
import viewImg from "@/components/public/viewImg.vue";
import { ElMessage, ElLoading } from "element-plus";
import {
  product,
  productAdd,
  productEdit,
  productDel,
  productStatus,
} from "@/http/api";
export default {
  name: "ProductList",
  components: {
    CoolPagination,
    CoolDialog,
    outMain,
    viewImg,
    cropper,
    CoolImageUploadVue,
    checkbox,
    switchComponent,
  },
  data() {
    return {
      // 审批详情
      showReviewMask: false,
      reviewForm: {
        listing_images: [
          {
            img: "https://tp.localbird.cn/uploads/20250804174039_142614_874175_ee26908bf9.",
          },
          {
            img: "https://tp.localbird.cn/uploads/20250813135333_486697_445571_ee26908bf9.",
          },
        ],
      },
      // 表格数据
      tableData: [
        {
          id: 1,
          name: "商品名称",
          image:
            "https://tp.localbird.cn/uploads/20250804174039_142614_874175_ee26908bf9.",
          price: 0,
          stock: 0,
        },
      ],
      // 请求参数
      queryData: {
        page: 1,
        per_page: 10,
        search_key: "",
      },
      total: 0,
      // 弹窗相关
      showMaskForm: false,
      isEdit: false,
      formData: {
        id: null,
        name: "",
        image: "",
        price: 0,
        stock: 0,
        description: "",
        status: true,
        tags: [],
        detail_images: "",
        detail_descriptions: "",
      },
      // 禁用状态开关
      disStatus: false,
      // 可用标签
      availableTags: [
        { value: "新品", label: "新品" },
        { value: "热卖", label: "热卖" },
        { value: "促销", label: "促销" },
        { value: "限时", label: "限时" },
        { value: "推荐", label: "推荐" },
        { value: "精选", label: "精选" },
        { value: "爆款", label: "爆款" },
        { value: "特价", label: "特价" },
      ],
    };
  },
  mounted() {
    // this.getData();
  },
  methods: {
    resetSearch() {
      this.queryData = {
        page: 1,
        per_page: 10,
        title: "",
      };
      this.searchFn();
    },
    handleDetail() {
      this.showReviewMask = true;
    },
    updateDetailImage(src) {
      this.formData.detail_images = src;
    },
    getImage(src) {
      this.formData.image = src;
    },
    // 获取商品列表数据
    async getData() {
      const loading = ElLoading.service({
        lock: true,
        text: "Loading",
        background: "rgba(255, 255, 255, 0.7)",
      });
      try {
        const res = await product(this.queryData);
        if (res) {
          res.data = res.data.map((item) => {
            item.status = item.status ? true : false;
            return item;
          });
          this.tableData = res.data;
          this.total = res.total;
        }
      } catch {}
      setTimeout(() => {
        loading.close();
      }, 100);
    },
    // 搜索处理
    searchFn() {
      this.queryData.page = 1;
      this.getData();
    },

    // 分页处理
    handlePageChange(page) {
      this.queryData.page = page;
      this.getData();
    },

    // 新增商品
    addFn() {
      this.isEdit = false;
      this.formData = {
        id: null,
        name: "",
        image: "",
        price: 0,
        stock: 0,
        description: "",
        status: true,
        tags: [],
        detail_images: "",
        detail_descriptions: "",
      };
      this.showMaskForm = true;
    },

    // 编辑商品
    handleEdit(item) {
      this.isEdit = true;
      const formData = JSON.parse(JSON.stringify(item));

      // 确保新增字段有默认值
      formData.tags = JSON.parse(formData.tags) || [];
      formData.detail_images = formData.detail_images || "";
      formData.detail_descriptions = formData.detail_descriptions || "";
      this.formData = formData;
      this.showMaskForm = true;
    },

    // 删除商品
    handleDelete(item) {
      this.$coolConfirm
        .confirm({
          title: "删除提示",
          message: "确定要删除该商品吗？",
          confirmButtonText: "确认",
          cancelButtonText: "取消",
        })
        .then(async () => {
          let queryData = {
            id: item.id,
          };
          const loading = ElLoading.service({
            lock: true,
            text: "Loading",
            background: "rgba(255, 255, 255, 0.7)",
          });
          try {
            const res = await productDel(queryData);
            if (res) {
              ElMessage.success("删除成功");
              this.getData();
            }
          } catch {}
          setTimeout(() => {
            loading.close();
          }, 100);
        })
        .catch(() => {});
    },
    validateForm() {
      if (!this.formData.name) {
        ElMessage.error("请输入商品名称");
        return false;
      } else if (!this.formData.image) {
        ElMessage.error("请上传商品图片");
        return false;
      } else if (!this.formData.price) {
        ElMessage.error("请输入商品价格");
        return false;
      } else if (!this.formData.stock) {
        ElMessage.error("请输入商品库存");
        return false;
      } else if (!this.formData.detail_images) {
        ElMessage.error("请上传商品详情图");
        return false;
      }
      return true;
    },
    // 确认新增/编辑
    async confirmDialog() {
      // 验证表单
      if (!this.validateForm()) {
        return;
      }
      let queryData = { ...this.formData };
      queryData["tags"] = JSON.stringify(queryData.tags);
      const loading = ElLoading.service({
        lock: true,
        text: "Loading",
        background: "rgba(255, 255, 255, 0.7)",
      });
      try {
        const res = this.isEdit
          ? await productEdit(queryData)
          : await productAdd(queryData);
        if (res) {
          ElMessage.success(this.isEdit ? "修改成功" : "添加成功");
          this.getData();
          this.showMaskForm = false;
        }
      } catch {
        //
      }
      setTimeout(() => {
        loading.close();
      }, 100);
    },

    // 修改商品状态
    async checkStatusFn(row) {
      this.disStatus = true;
      const status = row.status ? 1 : 0;
      try {
        const res = await productStatus({ id: row.id, status });
        if (res) {
          ElMessage.success("状态修改成功");
        } else {
          // 如果失败，回滚状态
          row.status = !row.status;
        }
      } catch {
        row.status = !row.status;
      } finally {
        setTimeout(() => {
          this.disStatus = false;
        }, 100);
      }
    },
  },
};
</script>
<style scoped lang="less"></style>
